function isHighVersion() {

	var version = navigator.userAgent.match(/Chrome\/(\d+)/)[1];

	return version > 9;

}



function i18nReplace(id, messageKey) {
    return $(id).html( chrome.i18n.getMessage(messageKey));
}



var bg = chrome.extension.getBackgroundPage();



var showimage = {

	canvas: document.createElement("canvas"),
	tabTitle: '',
	sessionId: '',
	host : 'https://zeenshare.com/',
	profileName : '',
	password : '',
	i18nReplace: i18nReplace,

	initCanvas: function() {

		document.getElementById('canvas').width = bg.screenshot.canvas.width;
		$('#photo').width(bg.screenshot.canvas.width);
		showimage.canvas.width =bg.screenshot.canvas.width;

		document.getElementById('canvas').height = bg.screenshot.canvas.height;
		$('#photo').height(bg.screenshot.canvas.height);
		showimage.canvas.height = bg.screenshot.canvas.height;
		var context = showimage.canvas.getContext('2d');
		context.drawImage(bg.screenshot.canvas, 0, 0);
		context = document.getElementById('canvas').getContext('2d');
		context.drawImage(showimage.canvas, 0, 0);
		$('#canvas').display = 'block';

	},



	init: function() {
		$('#error').hide();

	    i18nReplace('#createAccountLink', 'createAccountLink');
	    i18nReplace('#passwordLabel', 'password');
	    i18nReplace('#domainLabel', 'domain');
		
	    i18nReplace('#connectButton', 'connect');
	    i18nReplace('#rememberMeLabel', 'rememberMe');
	    i18nReplace('#loadingLabel', 'loading');
		

	    i18nReplace('#disconnect', 'disconnect');
	    i18nReplace('#propertiesLabel', 'fillProperties');
	    i18nReplace('#documentNameLabel', 'documentName');
	    i18nReplace('#folderLabel', 'folder');
	    i18nReplace('#send', 'send');
	    i18nReplace('#cancel', 'cancel');
	    i18nReplace('#uploadTitle', 'uploading');
		
		
		showimage.initCanvas();
		showimage.tabTitle = bg.screenshot.tab.title;
		this.connectWithAccount(localStorage.profileName, localStorage.pwd, localStorage.domain);
		

	},

	refreshAccount : function() {
		if(this.profileName && this.sessionId) {
			$('#account IMG').attr('src','https://zeenshare.com/api/account/get_icon?account='+this.profileName+'&sid='+this.sessionId);
			$('#profileName').html(this.profileName);
			$('#account').show();
		}else {
			$('#account').hide();
		}
	
	},
  

	connect : function() {

		this.profileName =  $('#nameInput').val() ;
		this.password =  $('#pwdInput').val() ;
		this.domain = $('#domainInput').val() ;
     
		if($('#rememberMeCheckbox').is(':checked')) {
			localStorage.profileName = this.profileName ;
			localStorage.pwd = this.password ;
			localStorage.domain = this.domain ;
		}
		this.connectWithAccount(this.profileName, this.password, this.domain );
	},

  

	connectWithAccount : function(profileName, password, domain) {
		this.hideAll();
		$('#loading').show();
		this.profileName = profileName;
		this.password = password;
		this.domain = domain;
		if(profileName && password) {
			var loginUrl = showimage.host+'api/auth?login='+profileName +'&pwd='+ password;
			if(this.domain) {
				loginUrl += '&teamName='+this.domain;
			}
			jQuery.getJSON(loginUrl, function(data) {
				if(data.apiHeader.status == 'OK') {
					showimage.sessionId = data.result.sessionId;
					showimage.refreshAccount();
					showimage.refreshFolders();
				} else {
					$('#error').show();
					showimage.showLoginForm();
				}
			});
		} else {
			showimage.showLoginForm();
		}

  	

	},

	refreshFolders : function() {
		this.hideAll();
		$('#loading').show();
		jQuery.getJSON(showimage.host+'api/project/get?level=1&sid='+showimage.sessionId, 
		function(jsonData) {
			if(jsonData.apiHeader.status == 'OK') {
				var folders = jsonData.result.folders;

				jQuery('#folderSelect').html('');
				jQuery('#folderSelect').append('<option value="">'+chrome.i18n.getMessage('rootFolder')+'</option>');
				for(var i = 0; i < folders.length; i++) {
					var folder = folders[i];
					jQuery('#folderSelect').append('<option value="'+folder.id+'">'+folder.name+'</option>');
				}
				showimage.showProperties();
			} else if(jsonData.apiHeader.errors[0].errorCode == "NO_SESSION_OPENED") {
				showimage.showLoginForm();
			}
		});

	},

  

	closeCurrentTab: function() {
		chrome.tabs.getSelected(null, function(tab) {
			chrome.tabs.remove(tab.id);
		});

	},

	showLoginForm: function() {
		$('#nameInput').val(this.profileName) ;
		$('#pwdInput').val( this.password ) ;
		$('#zeenshareAccountDiv').show();
		$('#properties').hide();
		$('#sendingDiv').hide();
		$('#loading').hide();
	},

	showProperties: function() {
		$('#zeenshareAccountDiv').hide();
		$('#sendingDiv').hide();
		$('#loading').hide();
		$('#properties').show();

	},
	hideAll: function() {
		$('#zeenshareAccountDiv').hide();
		$('#properties').hide();
		$('#sendingDiv').hide();
		$('#loading').hide();
		$('#account').hide();
		showimage.refreshAccount();

	},

	showUpload: function() {

		$('#sendingDiv').show();
		$('#zeenshareAccountDiv').hide();
		$('#properties').hide();

  	   

	},

	send : function() {
		if(!showimage.sessionId ){
			return showimage.showLoginForm();
		}
		this.showUpload();
		var img = showimage.getImageData();
		var documentName = $('#documentNameInput').val();
		documentName += '.png';
   

		var folderId = $('#folderSelect').val();
   

		var url = showimage.host+'api/document/upload?sid='+showimage.sessionId;
		if(folderId) {
			url += '&folderId='+folderId;
		}
   

		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4){
				var responseText = xhr.responseText;
				var jsonResponse = JSON.parse(responseText);
				if(jsonResponse.apiHeader.status = 'OK') {
					var folderId = $('#folderSelect').val();
             		var url = showimage.host+'home?sid='+showimage.sessionId+'#fs/1&doc/'+jsonResponse.result.documentId;
					url += '&nav/files/';
					if(folderId) {
						url += folderId;
					}
					window.open(
						url,
						"popup",
						"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1100,height=700");
						showimage.closeCurrentTab();
					} else {
						//TODO : show error
					}

				}

			};

			xhr.upload.addEventListener("progress",  function(progressEvent) {
				showimage.onProgress(progressEvent.loaded, progressEvent.total);

			}, false);

			if(xhr.upload) {
				xhr.upload.addEventListener("progress",  function(progressEvent) {
					if (progressEvent.lengthComputable) {
						showimage.onProgress(progressEvent.loaded, progressEvent.total);

					}

				}, false);

			}   

			xhr.open("POST", url, true);          

              

			// Set appropriate headers

			xhr.setRequestHeader("Content-Type", "multipart/form-data");
			xhr.setRequestHeader("X-File-Name", encodeURIComponent(documentName));
			xhr.setRequestHeader("X-File-Type", "image/png");
			xhr.setRequestHeader("X-File-Base", "base64");

			$('select.foo').val();   

      

			xhr.send(img);

		},

		onProgress : function(loaded, total) {
			if(loaded >= total) {
				$('#uploadedBar').width('100%');
	   		 	i18nReplace('#progressLabel', 'converting');

			} else {

				var width = loaded*100/total;
				width = Math.round(width);
				$('#uploadedBar').width(width+'%');
				$('#progressLabel').html(width+'%');

			}

		},

		openCreateAccountPopup : function() {

			window.open("https://zeenshare.com/signup_free",
			"popup",
			"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1000,height=700");

		},

		getImageData: function() {

			var dataUrl = document.getElementById('canvas').toDataURL('image/png');
			var imageDataIndex = dataUrl.indexOf('data:image/png;base64,');
			if (imageDataIndex != 0) {
				return;
			}

			return dataUrl.substr(imageDataIndex + 22);

		},
		disconnect : function() {
			this.profileName = null;
			this.sessionId = null;
			this.password = null;
			this.hideAll();
			this.showLoginForm();
		}
		

  

	};

	document.addEventListener("DOMContentLoaded", function() {
		$('#send').click(function() {
			showimage.send();
		});
		$('#cancel').click(function() {
			showimage.closeCurrentTab();
		});
		$('#connectButton').click( function() {
			showimage.connect();
			return false;
		});
		$('#createAccountLink').click( function() {		
			showimage.openCreateAccountPopup();		
			return false;	
		});
		
		$('#disconnect').click( function() {	
			showimage.disconnect();
			return false;	
		});
	
		showimage.init();
	});


